function _compressedImage(img: any) {
  const canvas = document.createElement('canvas');
  const ct = canvas.getContext('2d');
  const canvasWidth = img.width / 2;
  const canvasHeight = img.height / 2;
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;
  ct?.drawImage(img, 0, 0, canvasWidth, canvasHeight);
  const dataUrl = canvas.toDataURL('image/jpeg', 0.6);
  return dataUrl;
}

function readFile(file: Blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      const content = reader.result;
      if (content) {
        const img = new Image();
        img.src = content as string;
        resolve(img);
      }
    };
    reader.onerror = () => {
      reject(new Error('read file is not supported'));
    };
  });
}

function loadImg(img: any) {
  return new Promise((resolve, reject) => {
    img.onload = () => {
      resolve(img);
    };
    img.onerror = () => {
      reject(new Error('load img is not supported'));
    };
  });
}

function compressImage(files) {
  let compressedImageList = [];
  let fileLength = files.length;
  return new Promise((resolve, reject) => {
    for (var i = 0; i < fileLength; i++) {
      var file = files[i];
      readFile(file)
        .then((img) => {
          return loadImg(img);
        })
        .then((img) => {
          if (!img) {
            reject(new Error('compress image error'));
            return;
          }
          compressedImageList.push(_compressedImage(img));
          if (compressedImageList.length == fileLength) {
            resolve(compressedImageList);
          }
        });
    }
  });
}
export default compressImage;
